/*
   
   Copyright 2011 DAVID ALBERTSON, FRANCIS DESLAURIERS, ANTHONY BUFFET  &  DUINOP.COM

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
   
   Version 1.1b
*/

package com.gpsmap;

import java.io.IOException;
import java.util.Date;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;



public class GPSmap extends Activity implements LocationListener, OnClickListener{
    /** Called when the activity is first created. */
	
	// Declaration Layout
    private Button btnSender,btnMap;
	private String bestProvider,fastProvider;
	private TextView latText, lngText;
	private UserStatus currentUser;
	private LocationManager locationManager;
	private Criteria criteria;
	private String time;
	String version= "3"; // Phone version	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);        
        
        //Initialize the home page layout
        initializeLayout();
        
        //Creation of the currentUser with the last known postion and the unique id
        currentUser = new UserStatus(initializeLocationManager(), Secure.getString(getContentResolver(), Secure.ANDROID_ID));
       
        //Display de current user location on the home page
        displayPosition();        
        
	}
	
	//Shuts the provider down on Pause (to close the GPS)
	@Override
	protected void onPause(){
		super.onPause();
		locationManager.removeUpdates(this);
	}
	
	// Re-enables the GPS
	@Override
	protected void onResume(){
		super.onResume();
		 locationManager.requestLocationUpdates(bestProvider, 1, 0, this);
	}
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        return MenuChoice();
        
    }
        private void CreateMenu(Menu menu)
        {
                MenuItem mnu1 = menu.add(0, 0, 0, "About us!");
                {       
                        mnu1.setAlphabeticShortcut('a');
                }
                
        }
        
        private boolean MenuChoice ()
        {
        		AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
        		alertDialog.setTitle("About us");
        		alertDialog.setMessage("Made by : \nDavidAlbertson\nFrancis Deslauriers\nAnthony Green\n\nSources available at http://code.google.com/p/duinop/");
        		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        	      public void onClick(DialogInterface dialog, int which) {
        	    	  	// No need to do anything        	 
        	    } });

        		alertDialog.show();
                return true;
        }
	private void initializeLayout()
	{
       
         //Layout component
		 btnSender = (Button) findViewById(R.id.btnSender);
         btnMap = (Button) findViewById(R.id.btnMap);
         latText = (TextView)findViewById(R.id.textView1);
         lngText = (TextView)findViewById(R.id.textView2);        	
        	
            
         //Sets the logo size
         ImageView image = (ImageView) findViewById(R.id.test_image);
         Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.logoandroid);
         Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, 250, 250, true);
         image.setImageBitmap(bMapScaled);
		
         //Listener
         btnSender.setOnClickListener(this);
         btnMap.setOnClickListener(this);
	}

	private Location initializeLocationManager()
	{
        // Get current location
		// For exception list : http://developer.android.com/reference/android/location/LocationManager.html
        locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);	
        criteria = new Criteria();
        try{
        	criteria.setAccuracy(Criteria.ACCURACY_FINE); // For some reason ACCURACY FINE Causes issues when the cell has no FINE accuracy (after boot, in basement) TO VERIFY
        	int duration = Toast.LENGTH_SHORT;
            Toast.makeText(this, "Accuray Fine", duration).show();
        }
        catch(IllegalArgumentException e){
        	criteria.setAccuracy(Criteria.ACCURACY_COARSE); // If accuracy fine isn't working
        	int duration = Toast.LENGTH_SHORT;
            Toast.makeText(this, "Accuray Coarse", duration).show();
        }
        
        try{
        	fastProvider = LocationManager.NETWORK_PROVIDER;
        	
        }
        catch(IllegalArgumentException e){
        	AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
        	alertDialog.setTitle("Error 3");
        	alertDialog.setMessage("Connection problem");
        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        	      public void onClick(DialogInterface dialog, int which) {
        	    	  // No need to do anything   
        	    } });
        	alertDialog.setIcon(R.drawable.logoandroid);
        	alertDialog.show();	 
        }
        
        
           
        bestProvider = locationManager.getBestProvider(criteria, true);   
        locationManager.requestLocationUpdates(bestProvider, 1, 0, this);
       
       
        return locationManager.getLastKnownLocation(fastProvider);		
	}
		
    private void displayPosition()
    {
    	  String latitude = Float.toString(currentUser.getLatitude());
    	  String longitude = Float.toString(currentUser.getlongitude());
    	  latText.setText(latitude + " , ");
    	  lngText.setText(longitude);

    }
	
    private void getTime() {
		// TODO Auto-generated method stub
    	Date date = new Date();
		int hours = date.getHours();
        int minutes = date.getMinutes();
        int seconds = date.getSeconds();   
        int day = date.getDate();
        int month = date.getMonth();
        int year = date.getYear();
        time = year + "." + month + "." + day + "-" + hours + ":" + minutes + ":" + seconds;	
	}
    
    @Override
	public void onLocationChanged(Location location) {
		currentUser.SetPosition(location);
		displayPosition();
	}
	
	


	@Override
	

	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onClick(View arg0) {
		
		switch(arg0.getId()){
		
			case R.id.btnSender:
			{
			//	Toast.makeText(this, currentUser.getCountry()+currentUser.getLanguage()+currentUser.getLatitude()+currentUser.getlongitude()+currentUser.getManufacturer()+currentUser.getModel()+currentUser.getOsVersion()+currentUser.getTimeSinceLastBootInSeconds() +currentUser.getUniqueID(), Toast.LENGTH_SHORT).show();
			
				getTime();
				postData();	
				break;
			}
			
			case R.id.btnMap:
			{
				HttpClient httpclient = new DefaultHttpClient();
		        HttpPost httppost_map = new HttpPost("http://www.incognitoproject.com/duinop/map/index2.html");
		        
		        try {		        	
		            HttpResponse response = httpclient.execute(httppost_map);
		            startActivity(new Intent(getBaseContext() ,map.class));
		            
		        } catch (ClientProtocolException e) {
		        	AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
		        	alertDialog.setTitle("Error 1");
		        	alertDialog.setMessage("Connection problem");
		        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
		        	      public void onClick(DialogInterface dialog, int which) {
		        	    	  // No need to do anything   
		        	    } });
		        	alertDialog.setIcon(R.drawable.logoandroid);
		        	alertDialog.show();	        	

		        } catch (IOException e) {
		        	AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
		        	alertDialog.setTitle("Error 2");
		        	alertDialog.setMessage("Connection problem");
		        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
		        	      public void onClick(DialogInterface dialog, int which) {
		        	    	  	// No need to do anything        	 
		        	    } });

		        	alertDialog.show();
		        }
		        
				break;
			}
		}
		
	}
    
	
	public void postData() {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost_map = new HttpPost("http://www.incognitoproject.com/duinop/phoneRequest.php?lat=" + currentUser.getLatitude() + "&long=" + currentUser.getlongitude()+ "&unique=" + currentUser.getUniqueID() + "&ver=" + version + "&time=" + time + "&messg=" + currentUser.getMessage());
        HttpPost httppost_globe = new HttpPost("http://www.incognitoproject.com/duinop/globe/updateGlobeData.php?lat=" + currentUser.getLatitude() + "&lon=" + currentUser.getlongitude() + "&userID=" + currentUser.getUniqueID());
        	
        	
        try {
        	/*
        	 * 
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("long", "38.6958"));
            nameValuePairs.add(new BasicNameValuePair("lat", "-110.002442"));
           // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
            
            */
            HttpResponse response = httpclient.execute(httppost_map);
            HttpResponse response1 = httpclient.execute(httppost_globe);
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(this, "Position posted", duration).show();
        } catch (ClientProtocolException e) {

        	AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
        	alertDialog.setTitle("Error 1");
        	alertDialog.setMessage("Connection problem");
        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        	      public void onClick(DialogInterface dialog, int which) {
        	    	  // No need to do anything   
        	    } });
        	alertDialog.setIcon(R.drawable.logoandroid);
        	alertDialog.show();
        	
        	
            // TODO Auto-generated catch block
        } catch (IOException e) {
        	AlertDialog alertDialog = new AlertDialog.Builder(GPSmap.this).create();
        	alertDialog.setTitle("Error 2");
        	alertDialog.setMessage("Connection problem");
        	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        	      public void onClick(DialogInterface dialog, int which) {
        	    	  	// No need to do anything        	 
        	    } });

        	alertDialog.show();
            // TODO Auto-generated catch block
        }
        
              
    }

}
